package com.xbongbong.pro.controller.exception;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ImportErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.Objects;

/**
 * 统一异常处理
 * @author kaka
 * @time 2018-9-18 14:46
 */
@ControllerAdvice
public class ExceptionHandle {

    private static final Logger LOG = LoggerFactory.getLogger(ExceptionHandle.class);

    /**
     * 将controller层出现的异常捕获，记录error日志
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public String exceptionHandle(Exception e) {
        XbbResponse response;
        if (e instanceof XbbException) {
            response = new XbbResponse((XbbException)e);
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            response = new XbbResponse(new XbbException(SystemErrorCodeEnum.API_ERROR_100002, I18nStringConstant.ONLY_SUPPORTS_POST_REQUESTS));
        } else if (e instanceof MethodArgumentNotValidException) {
            response = new XbbResponse(new XbbException(SystemErrorCodeEnum.API_ERROR_100002, Objects.requireNonNull(((MethodArgumentNotValidException) e).getBindingResult().getFieldError()).getDefaultMessage()));
        } else if (e instanceof HttpMessageNotReadableException) {
            response = new XbbResponse(new XbbException(SystemErrorCodeEnum.API_ERROR_100064));
        } else if (e instanceof MaxUploadSizeExceededException) {
            String maxFileSize = ProBaseConfig.getMaxFileSize();
            if (StringUtil.isEmpty(maxFileSize)) {
                response = new XbbResponse(new XbbException(ImportErrorCodeEnum.API_ERROR_235057));
            } else {
                response = new XbbResponse(new XbbException(ImportErrorCodeEnum.API_ERROR_235056, ImportErrorCodeEnum.API_ERROR_235056.getMsg(), maxFileSize));
            }
        } else {
            response = new XbbResponse(new XbbException(SystemErrorCodeEnum.API_ERROR_100063));
        }
        LOG.error("ExceptionHandle.exceptionHandle 截获异常 : ", e);

        return JSON.toJSONString(response);
    }
}
